 package cn.uexpo.lhz.controller.admin;


 import cn.uexpo.lhz.biz.ImportLogBiz;
 import cn.uexpo.lhz.biz.StaffBiz;
 import cn.uexpo.lhz.biz.StaffImportErrorBiz;
 import cn.uexpo.lhz.common.oldBase.BaseController;
 import cn.uexpo.lhz.common.oldUtils.PageResult;
 import cn.uexpo.lhz.common.oldUtils.StringDate;
 import cn.uexpo.lhz.common.utils.BeanCopyUtils;
 import cn.uexpo.lhz.common.utils.StringUtil;
 import cn.uexpo.lhz.core.http.HttpResult;
 import cn.uexpo.lhz.domain.*;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;

 import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.util.Date;
 import java.util.List;
 import java.util.regex.Pattern;


 @RestController
 @RequestMapping("/admin/staffErrorImport")
 public class StaffErrorImportController extends BaseController<StaffImportError>{

     @Autowired
     private StaffImportErrorBiz staffErrorBiz;
     @Autowired
     private StaffBiz staffBiz;
     @Autowired
     private ImportLogBiz importLogBiz;



//     @PostMapping(value="/findPage")
//     public HttpResult findPage(@RequestBody cn.uexpo.lhz.common.oldUtils.PageRequest pageRequest) {
//         PageResult result=findPage1(pageRequest);
//         return HttpResult.ok(result);
//     }


//     private PageResult findPage1(@RequestBody cn.uexpo.lhz.common.oldUtils.PageRequest pageRequest) {
//
//         Object proType = pageRequest.getParamValue("proType");//项目类型
//         Object fileName = pageRequest.getParamValue("fileName");//文件名
//         Object code = pageRequest.getParamValue("code");//返回码
//         Object staffName = pageRequest.getParamValue("staffName");//姓名
//
//         StaffImportErrorExample example=new StaffImportErrorExample();
//         String orderBy=" into_time ";//默认按照时间降序
//         String sort=" desc ";//默认按照时间降序
//         example.setOrderByClause(orderBy+sort);
//         StaffImportErrorExample.Criteria citeria=example.createCriteria();
//         if (StringUtils.isNotBlank((String)proType)) {
//             citeria.andProjectTypeEqualTo((String)proType);
//         }
//         if (StringUtils.isNotBlank((String)fileName)) {
//             citeria.andUntitled14EqualTo((String)fileName);
//         }
//         if (StringUtils.isNotBlank((String)code)) {
//             citeria.andUntitled11EqualTo((String)code);
//         }
//         if (StringUtils.isNotBlank((String)staffName)) {
//             citeria.andStaffNameLike("%"+(String)staffName+"%");
//         }
//
//         PageResult result=staffErrorBiz.findPage(pageRequest,example);
//         return result;
//     }


     /**
      * 纠错
      * @param
      * @return
      * @throws Exception
      */
     @PostMapping(value="/staffRepair")
     public HttpResult staffRepair(@RequestBody StaffImportError staffError) {
         String msg="";
         int resultcode=0;

         if (StringUtils.isBlank(staffError.getStaffName())){//如果姓名为空，跳过该记录
             resultcode=101;
             msg="姓名不允许为空";
             staffError.setUntitled15(msg);
             return repairCancel(staffError,resultcode);
         }

         String recordFlag = "0";//记录判断
         String namelenthFlag="0";//姓名长度
         String untitled2Flag="0";//人员编号长度
         String untitled6Flag="0";//进入场次次数限制
         String untitled7Flag="0";//入场开始时间
         String untitled8Flag="0";//入场结束时间

         int no = 0;
         Date currentTime=StringDate.getNow();
         String keyword1 = staffError.getUntitled2();// 人员编号
         String keyword2 = staffError.getStaffName();// 姓名
         String inCountLimit = staffError.getUntitled6();//进入场次次数限制，默认0  untitled6
         String allowInTime = staffError.getUntitled7();//允许入场开始时间 untitled7
         String allowOutTime = staffError.getUntitled8();//允许入场结束时间 untitled8

         namelenthFlag=verifyNamelenth(keyword2);
         untitled2Flag=verifyUntitled2(keyword1);
         untitled6Flag=verifyNumFMT(inCountLimit);
         untitled7Flag=verifyTimeFMT(allowInTime);
         untitled8Flag=verifyTimeFMT(allowOutTime);
         recordFlag = verifyRecord(staffError);

         //姓名长度判断
         if (namelenthFlag.equals("1")) {
             resultcode=101;
             msg="姓名长度不能超过200";
             staffError.setUntitled15(msg);
             return repairCancel(staffError,resultcode);
         }
         //人员编号长度判断
         if (untitled2Flag.equals("1")) {
             resultcode=101;
             msg="人员编号长度不能超过200";
             staffError.setUntitled15(msg);
             return repairCancel(staffError,resultcode);
         }

         //入进入场次次数限制  0和正整数 格式判断
         if (untitled6Flag.equals("1")) {
             resultcode=101;
             msg="进入场次次数限制格式不正确";
             staffError.setUntitled15(msg);
             return repairCancel(staffError,resultcode);
         }else if (untitled6Flag.equals("2")) {
             staffError.setUntitled6("0");
         }else {
             staffError.setUntitled6(inCountLimit);
         }
         //入场开始时间格式判断
         if (untitled7Flag.equals("1")) {
             resultcode=101;
             msg="入场开始时间不符合日期格式要求";
             staffError.setUntitled15(msg);
             return repairCancel(staffError,resultcode);
         }else if (untitled7Flag.equals("2")) {
             staffError.setUntitled7(null);
         }else{
             Date allowInTime1=StringDate.getDateTime1(allowInTime);
             allowInTime = StringDate.DateToString(allowInTime1);
             staffError.setUntitled7(allowInTime);
         }

         //入场结束时间格式判断
         if (untitled8Flag.equals("1")) {
             resultcode=101;
             msg="入场结束时间不符合日期格式要求";
             staffError.setUntitled15(msg);
             return repairCancel(staffError,resultcode);
         }else if (untitled8Flag.equals("2")) {
             staffError.setUntitled8(null);
         }else{
             Date allowOutTime1=StringDate.getDateTime1(allowOutTime);
             allowOutTime = StringDate.DateToString(allowOutTime1);
             staffError.setUntitled8(allowOutTime);
         }


         if (recordFlag.equals("1")) {//已存在，
             resultcode=101;
             msg="违反 姓名,项目名,身份证唯一性约束";
             staffError.setUntitled15(msg);
             return repairCancel(staffError,resultcode);
         }
         staffError.setIntoAccount("批量导入_纠错更新");
         staffError.setIntoTime(currentTime);

         return repairSubmit(staffError);

     }

     /**
      * 删除
      * @param
      * @return
      * @throws Exception
      */

     @RequestMapping(value="/delete",method=RequestMethod.POST)
     public HttpResult dictDelete(@RequestBody List<StaffImportError> records) throws Exception {
         int result=0;
         try {
             result= staffErrorBiz.delete(records);
             //同时删除日志记录
             if(records!=null&&records.size()>0){
                 for (StaffImportError record : records) {
                     String staffId = record.getStaffId()+"";
                     ImportLogExample example=new ImportLogExample();
                     ImportLogExample.Criteria citeria=example.createCriteria();
                     citeria.andExtstr1EqualTo(staffId);
                     List<ImportLog> list = importLogBiz.selectByExample(example);
                     if(list!=null&&list.size()>0){
                         importLogBiz.delete(list);
                     }
                 }
             }

         } catch (Exception e) {
             result=0;
         }

         return HttpResult.ok(result);

     }


     //提交修复
     private HttpResult repairSubmit(StaffImportError staffError){

         int no = 0;
         Staff staff = new Staff();
         try {
             BeanCopyUtils.Copy(staffError,staff);
             Date currentTime=StringDate.getNow();
             staff.setStaffId(null);
             staff.setUntitled12(null);
             staff.setUntitled13(null);
             staff.setIntoTime(currentTime);//纠错入staff表时间
             staff.setStaffState("0");//状态（正常0或者停用1）
             no = staffBiz.insert(staff);
             //纠错成功，更新导入日志
             if(no==1){
                 ImportLogExample example=new ImportLogExample();
                 ImportLogExample.Criteria citeria=example.createCriteria();
                 String staffId =staffError.getStaffId()+"";
                 citeria.andExtstr1EqualTo(staffId);

                 ImportLog log = null;
                 List<ImportLog> list = importLogBiz.selectByExample(example);
                 if(list!=null&&list.size()>0){
                     log = new ImportLog();
                     Date now = StringDate.getNow();
                     log=list.get(0);
                     log.setCode(200);
                     log.setMsg("纠错成功");
                     log.setCreateBy(staffError.getUntitled12());
                     log.setKeyword2(staffError.getStaffName());//更新姓名
                     log.setKeyword3(staffError.getStaffTel());//更新手机号
                     log.setCreateTime(now);
                     int updateNo= importLogBiz.updateByPrimaryKeySelective(log);
                     if(updateNo==1){
                         //删除错误记录
                         staffErrorBiz.deleteByPrimaryKey(staffError.getStaffId());
                     }
                 }
             }
             log.info(staff+"--------error");
         } catch (Exception e) {
             e.printStackTrace();
         }


         return HttpResult.ok(no);

     }
     //撤销修复
     private HttpResult repairCancel(StaffImportError staffError , int resultcode){
         int no = 0;
         String errorNumStr=staffError.getUntitled13();
         int errorNum = 0 ;
         if(StringUtil.isNotBlank(errorNumStr)){
             errorNum= Integer.parseInt(errorNumStr)+1;
             staffError.setUntitled13(errorNum+"");
         }else{
             staffError.setUntitled13("1");
         }
         no = staffErrorBiz.updateByPrimaryKeySelective(staffError);
         updateImportLog(staffError,resultcode);
         return HttpResult.ok(no);
     }


     private void updateImportLog(StaffImportError staffError, int resultcode) {

         ImportLogExample example=new ImportLogExample();
         ImportLogExample.Criteria citeria=example.createCriteria();
         String staffId =staffError.getStaffId()+"";
         citeria.andExtstr1EqualTo(staffId);

         ImportLog log = null;
         List<ImportLog> list = importLogBiz.selectByExample(example);
         if(list!=null&&list.size()>0){
             log = new ImportLog();
             log=list.get(0);
         }

         String createBy = "" ;
         String fileName = "" ;
         String msg = "" ;
         if(log!=null){
             createBy = staffError.getUntitled12() ;
             fileName = staffError.getUntitled14() ;
             msg = staffError.getUntitled15() ;
         }

         Date now = StringDate.getNow();
         String keyword1 = staffError.getUntitled2();// 人员编号
         String keyword2 = staffError.getStaffName();// 姓名
         String keyword3 = staffError.getStaffTel();// 手机号
         String keyword4 = staffError.getProjectType();// 所属项目
         log.setCode(resultcode);
         log.setMsg(msg);
         log.setFilename(fileName);
         log.setKeyword1(keyword1);
         log.setKeyword2(keyword2);
         log.setKeyword3(keyword3);
         log.setKeyword4(keyword4);
         log.setCreateBy(createBy);
         log.setCreateTime(now);
         importLogBiz.updateByPrimaryKeySelective(log);
     }







     //姓名长度
     private String verifyNamelenth(String name) {
         String result = "0";
         if (StringUtils.isNotBlank(name)) {
             if (name.length()>=200) {
                 result = "1";//长度越界
             }
         }
         return result;
     }
     //人员编号长度
     private String verifyUntitled2(String untitled2) {
         String result = "0";
         if (StringUtils.isNotBlank(untitled2)) {
             if (untitled2.length()>=200) {
                 result = "1";//长度越界
             }
         }
         return result;
     }

     //是否为非负整数格式
     private String verifyNumFMT(String pramStr) {
         String result = "0";
         if (StringUtils.isNotBlank(pramStr)) {
             String pattern = "^\\d+$";
             boolean isMatch = Pattern.matches(pattern, pramStr);
             if(!isMatch){
                 result = "1";//不匹配
             }else{
                 result = "0";//匹配
             }
         }else{
             result = "2";//为空
         }
         return result;
     }
     //是否为日期格式
     private String verifyTimeFMT(String timeStr) {
         String result = "0";//符合要求
         Date time = null;
         if (StringUtils.isNotBlank(timeStr)) {
             try{
                 time = StringDate.getDateTime1(timeStr);
                 if(time==null){
                     result = "1";//不符合要求
                 }
             }catch (Exception e){
                 result = "1";//不符合要求
             }

         }else{
             result = "2";
         }
         return result;
     }
     //图片
     private String verifyPic(List<File> files, Staff staff) throws IOException {
         String FILE_SIZE=dictionaryUtil.getItemValueUsable("biz_staff_params","staff_pic_size");//图片大小：单位M
         String result = "0";//默认找不到图片
//        String recordPicname = staff.getStaffName() + "_" + staff.getStaffTel();//从excel文件中设置图片名字
         String recordPicname = staff.getUntitled2();//人员编号作为图片名称
         for (File picFile : files) {
             String picfileName = picFile.getName();
             String picfileName1 = picfileName.substring(0, picfileName.indexOf("."));//获取图片名字，不带后缀
             if (recordPicname.equals(picfileName1)) {
                 staff.setUntitled3(picfileName);//图片名称
                 long size=picFile.length();
                 if (size>Long.parseLong(FILE_SIZE)*1024*1024) {
                     result = "2";//图片超过4M不符合要求
                     break;
                 }else {
//                    String res ="";
//                    try {
//                        FileInputStream input = new FileInputStream(picFile);
//                        byte[] buf = new byte[1024*1024*10]; //数据中转站 临时缓冲区
//                        int length = 0;
//                        //循环读取文件内容，输入流中将最多buf.length个字节的数据读入一个buf数组中,返回类型是读取到的字节数。
//                        //当文件读取到结尾时返回 -1,循环结束。
//                        while((length = input.read(buf)) != -1){
//                            String ss=new String(buf, 0, length);
////                            System.out.println(ss+"-----------");
//                        }
//                        MultipartFile multipartFile =  new MockMultipartFile("file", picFile.getName(), "text/plain", buf);
//                        //请求图片上传结果
//                        String key = "b1e899132c9bf7032b/*b86d6f9bc240e4";
//                        String url1 = "http://sf.uexpo.cn:8080/tool/face6";
//                        String cardType = "2";
//                        Map<String,String> param = new HashMap<>();
//                        param.put("key", key);
//                        param.put("cardType", cardType);
//                        res = HttpClientUtils.uploadFile(url1, multipartFile, "repayFile", null, null);
//                    } catch (FileNotFoundException e1) {
//                        // TODO Auto-generated catch block
//                        e1.printStackTrace();
//                    }
//                    if (StringUtils.isNotBlank(res)&&res.length()>0) {
//                        byte[] readAllBytes = Files.readAllBytes(picFile.toPath());//获取文件的字节数组
//                        staff.setStaffOriginalImage(readAllBytes);
//
//                        staff.setStaffHeadImage(Base64.decodeBase64(res));//抠图内容
//                        result = "1";//找到图片
//                        break;
//                    }else{
//                        result = "3";//调用opencv接口 抠图失败
//                        break;
//                    }

                     byte[] readAllBytes = Files.readAllBytes(picFile.toPath());//获取文件的字节数组
                     staff.setStaffOriginalImage(readAllBytes);
                     result = "1";//找到图片
                     break;
                 }
             }
         }

         return result;
     }
     //是否有记录
     @SuppressWarnings("rawtypes")
     private String verifyRecord(StaffImportError staffError) {
         String result = "0";//默认无记录
         StaffExample example = new StaffExample();
         StaffExample.Criteria citeria = example.createCriteria();
         List staffs = null;
         if (StringUtils.isNotBlank(staffError.getStaffName())
                 && StringUtils.isNotBlank(staffError.getProjectType())
                 && StringUtils.isNotBlank(staffError.getStaffCardid())) {
             citeria.andStaffNameEqualTo(staffError.getStaffName()).andProjectTypeEqualTo(staffError.getProjectType()).andStaffCardidEqualTo(staffError.getStaffCardid());
             staffs = staffBiz.selectByExample(example);
         }
         if (staffs != null && staffs.size() > 0) {
             result = "1";//有记录
         }
         return result;
     }



 }
